package com.cloud.mall.consume.config;

import com.cloud.mall.consume.service.ErrorService;
import com.cloud.mall.enums.ErrorLogEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * ErrorService工厂<br>
 * 将各个实现类放入map
 *
 */
@Configuration
public class ErrorLogFactory {

    private Map<ErrorLogEnum, ErrorService> map = new HashMap<>();

    @Autowired
    private ErrorService esServiceImpl;
    @Autowired
    private ErrorService dbServiceImpl;
    @Autowired
    private ErrorService  mongodbServiceImpl;

    @PostConstruct
    public void init() {
        map.put(ErrorLogEnum.ES, esServiceImpl);
        map.put(ErrorLogEnum.DB, dbServiceImpl);
        map.put(ErrorLogEnum.MONGODB, mongodbServiceImpl);
    }

    /**
     * 根据错误来源找到对应的方法
     *
     * @param errSource
     * @return
     */
    public ErrorService getErrorService(String errSource) {
        if (StringUtils.isBlank(errSource)) {// 默认用本地存储
            return dbServiceImpl;
        }

        ErrorService errorService = map.get(ErrorLogEnum.valueOf(errSource));
        if (errorService == null) {
            throw new IllegalArgumentException("请检查ErrorLogFactory类的init方法，看是否有" + errSource + "对应的实现类");
        }
        return errorService;
    }
}
